<template>
  <view class="content">
    <!--LOGO-->
    <view class="logo">
      <u-image
          src="/static/LOGO_raw.png"
          height="auto"
          :width="register_status?'50vw':'60vw'"
          mode="widthFix"
      ></u-image>
    </view>
    <u-toast ref="uToast"></u-toast>
    <!-- 注册信息 -->
    <view class="register" v-show="register_status">
      <!-- 标题 -->
      <view>
        <text class="reg-title">完善信息</text>
      </view>
      <u--form :model="register_form" :rules="rules" ref="form1">
        <u-form-item label="姓名" prop="name" ref="register_form.name">
          <u-input
              v-model="register_form.name"
              placeholder="请输入您的真实姓名"
              maxlength="4"></u-input>
        </u-form-item>
        <u-form-item label="电话" prop="tel" ref="register_form.tel">
          <view class="tel">
            <u-input
                v-model="register_form.tel"
                placeholder="请输入您在用的电话号码"
                type="number">
            </u-input>
          </view>
        </u-form-item>
        <u-form-item label="邮箱" prop="email" ref="register_form.email">
          <u-input
              v-model="register_form.email"
              placeholder="请输入您常用的电子邮箱"
          ></u-input>
        </u-form-item>
      </u--form>
      <!-- 点击继续 -->
      <view class="reg-btn">
        <u-button
            shape="circle"
            ripple="ripple"
            type="primary"
            color="#212121"
            plain
            @click="submit"
            :disabled="!btnStatus">点击继续
        </u-button>
      </view>
    </view>
    <!-- 登录按钮 -->
    <view class="btn" v-show="!register_status">
      <u-button
          shape="circle"
          ripple="ripple"
          type="primary"
          size="large"
          color="#212121"
          @click="login"
          :disabled="!btnStatus"
      >点击开始
      </u-button>
    </view>
    <!-- 文本 -->
    <view class="text-area">
      <text class="msg">{{ msg }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      msg: '“好借好还，再借不难。”',
      register_status: false,
      register_form: {
        openId: '',
        name: '',
        tel: '',
        email: '',
        role: 0,
        avatarUrl: ''
      },
      rules: {
        name: {
          type: 'string',
          required: true,
          message: '请填写姓名',
          trigger: ['blur', 'change']
        },
        tel: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur']
          },
          {
            validator: (rule, value, callback) => {
              // 返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }
        ],
        email: [
          {
            required: true,
            message: '请填写邮箱',
            trigger: ['blur', 'change']
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.email(value)
            },
            message: '请填写正确的邮箱',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }
        ]
      },
      btnStatus: true
    }
  },
  onLoad() {

  },
  methods: {
    async login() {
      let _this = this
      this.btnStatus = false
      //获取openID
      let userObj = uniCloud.importObject('user')
      uni.login({
        //登录成功
        success: async res => {
          //调用云函数获取OpenId
          let userInfo = await userObj.getOpenId(res.code)
          this.register_form.openId = userInfo.openid
          //保存openId至本地
          uni.setStorageSync('openId', userInfo.openid)
          //查询数据库是否存在此用户
          const db = uniCloud.database()
          const _res = await db.collection('user')
              .where({
                openId: userInfo.openid
              })
              .get()
          //判断是否存在该用户
          if (_res.result.data.length > 0) {
            await this.getUserInfo(userInfo.openid)
          } else {
            //不存在该用户，进行信息注册
            this.register_status = true
            _this.btnStatus = true
          }
        },
        fail: err => {
          this.$refs.uToast.show({
            message: '微信登录失败',
            type: 'error',
            position: 'top',
            complete() {
              _this.btnStatus = true
            }
          })
        }
      })
    },
    //点击继续
    submit() {
      let _this = this
      this.btnStatus = false
      const openId = this.register_form.openId
      this.$refs.form1.validate().then(async res => {
        //新增用户
        const db = uniCloud.database()
        await db.collection('user').add(this.register_form)
            .then(res => {
              this.$refs.uToast.show({
                message: '注册成功',
                type: 'success',
                position: 'top',
                complete() {
                  //保存信息
                  uni.setStorageSync('openId', openId)
                  _this.register_form._id = res.result.id
                  uni.setStorageSync('userInfo', _this.register_form)
                  //跳转借还页
                  uni.switchTab({
                    url: '/pages/Switch'
                  })
                }
              })
            })
            .catch(err => {
              this.$refs.uToast.show({
                message: err.data.errMsg || '注册失败',
                type: 'error',
                position: 'top',
                complete() {
                  _this.btnStatus = true
                }
              })
            })
      })
    },
    //获取用户信息
    async getUserInfo(openId) {
      this.btnStatus = false
      let _this = this
      //从数据库获取
      const database = uniCloud.database()
      const user = database.collection('user')
      let res = await user.where({
        openId: openId
      }).get()
      //保存至本地
      //1.检查请求是否成功
      if (res.success === true) {
        //2. 检查是否查询到数据
        if (res.result.data.length > 0) {
          // 保存数据
          uni.setStorageSync('userInfo', res.result.data[0])
          uni.switchTab({
            url: '/pages/Switch'
          })
        } else {
          // 没有用户数据，重新注册
          this.$refs.uToast.show({
            message: '没有此用户信息，请重新注册',
            type: 'error',
            position: 'top',
            complete() {
              _this.register_status = true
              _this.btnStatus = true
            }
          })
        }
      } else {
        //查询失败
        this.$refs.uToast.show({
          message: '查询用户信息失败，请重试',
          type: 'error',
          position: 'top'
        })
      }
      this.btnStatus = true
    }
  },
  onReady() {
    this.$refs.form1.setRules(this.rules)
  }
}
</script>

<style lang="scss">
.content {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

.logo {
  margin-top: 10vh;
}

.btn {
  width: 50%;
  margin-bottom: 10vh;
}

.text-area {
  margin-bottom: 10vh;
  display: flex;
  justify-content: center;
}

.msg {
  font-size: 10px;
  color: $uni-text-color-grey;
}

/* 注册信息 */
.register {
  margin-top: 10vh;
  margin-bottom: 5vh;
  width: 300px;
  justify-content: center;

  .reg-title {
    display: flex;
    justify-content: center;
    font-size: $uni-font-size-lg;
    font-weight: bold;
    color: $uni-text-color;
    margin-bottom: 20px;
  }

  .tel {
    display: flex;

    .tel-btn {
      margin-left: 5px;
      width: 100px;
    }
  }

  .reg-btn {
    margin-top: 30px;
  }
}
</style>
